package net.viservice;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.viservice.mysql.backup.DataBaseBackupJob;
import net.viservice.mysql.backup.PrintTimeJob;
import net.viservice.util.PropertiesUtils;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;

public class MainApplaction implements WrapperListener {

	private static Logger logger = LoggerFactory.getLogger(MainApplaction.class);

	private static Scheduler scheduler;

	public static void main(String[] args) {
		WrapperManager.start((new MainApplaction()), args);
	}

	@Override
	public void controlEvent(int event) {
		logger.debug("Exec: controlEvent(" + event + ")");
		if (event == WrapperManager.WRAPPER_CTRL_LOGOFF_EVENT) {
			if (WrapperManager.isLaunchedAsService() || WrapperManager.isIgnoreUserLogoffs()) {
				logger.debug("中间件服务:忽略注销事件");
			} else {
				WrapperManager.stop(0);
			}
		} else if (event == WrapperManager.WRAPPER_CTRL_C_EVENT) {
			logger.debug("中间件服务:忽略CTRL+C事件");
		} else {
			WrapperManager.stop(0);
		}
	}

	@Override
	public Integer start(String[] args) {
		logger.info("程序已经启动");

		try {
			Properties config = null;
			try {
				InputStream in = MainApplaction.class.getClass().getResourceAsStream("/config.properties");
				config = new Properties();
				config.load(in);
				in.close();
			} catch (Exception e) {
				throw new Exception("读取配置文件config.properties失败！");
			}
			
			PropertiesUtils propertiesUtils = new PropertiesUtils(config);

			String fileName = "quartz.properties";
			// SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			SchedulerFactory schedulerFactory = new StdSchedulerFactory(fileName);
			scheduler = schedulerFactory.getScheduler();

			Class<PrintTimeJob> jobClass = PrintTimeJob.class;
			String jobName = jobClass.getName();
			Map<String, Object> dataMap = new HashMap<String, Object>();
			String cronExpression = "0/30 * * * * ?";// 每10秒执行一次

			scheduleJob(jobName, jobClass, dataMap, cronExpression);

			// 数据库备份Job
			Class<DataBaseBackupJob> jobClass4DbBackup = DataBaseBackupJob.class;
			String jobName4DbBackup = jobClass4DbBackup.getName();
			Map<String, Object> dataMap4DbBackup = new HashMap<String, Object>();
			dataMap4DbBackup.put("mysqlRootPath", propertiesUtils.get("database.mysql.backup.mysqlRootPath"));
			dataMap4DbBackup.put("mysqlUser", propertiesUtils.get("database.mysql.backup.mysqlUser"));
			dataMap4DbBackup.put("mysqlPassword", propertiesUtils.get("database.mysql.backup.mysqlPassword"));
			dataMap4DbBackup.put("databaseName", propertiesUtils.get("database.mysql.backup.databaseName"));
			dataMap4DbBackup.put("backupFileRootPath", propertiesUtils.get("database.mysql.backup.backupFileRootPath"));
			dataMap4DbBackup.put("history", propertiesUtils.get("database.mysql.backup.history"));
			String cronExpression4DbBackup = propertiesUtils.getRequiredString("database.mysql.backup.cronExpression");
			scheduleJob(jobName4DbBackup, jobClass4DbBackup, dataMap4DbBackup, cronExpression4DbBackup);

			scheduler.start();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public int stop(int exitCode) {
		if (scheduler != null) {
			try {
				// 关闭调度器
				scheduler.shutdown(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return exitCode;
	}

	public static void scheduleJob(String jobName, Class jobClass, Map<String, Object> dataMap, String cronExpression) {
		String jobGroup = "defaultGroup";
		scheduleJob(jobGroup, jobName, jobClass, dataMap, cronExpression);
	}

	public static void scheduleJob(String jobGroup, String jobName, Class jobClass, Map<String, Object> dataMap, String cronExpression) {
		try {
			if (scheduler == null) {
				String message = "scheduler不能为空！";
				logger.error(message);
				throw new Exception(message);
			}

			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build();
			// 遍历参数，压入JobDateMap
			for (String key : dataMap.keySet()) {
				jobDetail.getJobDataMap().put(key, dataMap.get(key));
			}

			// 表达式调度构建器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

			// 按新的cronExpression表达式构建一个新的trigger
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobDetail.getKey().getName(), jobDetail.getKey().getGroup()).withSchedule(cronScheduleBuilder).build();

			scheduler.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

}
